<template>
  <div class="jx-login-wrap" @keypress.enter="Login">
    <div class="login-left">
      版权所有：华育兴业 电话：010-82340234
      <br />
      地址：北京市海淀区中关村软件园东北旺南路29号首农蓝海中心C座7层
    </div>
    <div class="login-right">
      <div class="jx-login-window">
        <div class="jx-login-logo">
          <img :src="unauthorizedLogoImage" />
          <span>{{ projectName }}</span>
        </div>
        <div class="jx-login-main">
          <div class="jx-login-title">
            <img src="@/assets/images/login-logo-2.png" alt="" />
          </div>
          <form class="jx-login-form">
            <div class="jx-login-form-item jx-login-imgbox jx-login-name">
              <input
                type="text"
                v-model="account"
                placeholder="请输入账号"
                @focus="accountDown"
              />
              <img src="@/assets/images/login-name.png" alt="" />
            </div>
            <div class="jx-login-form-item jx-login-imgbox jx-login-pwd">
              <input
                type="password"
                v-model="password"
                autocomplete="off"
                placeholder="请输入密码"
                @focus="pwdDown"
              />
              <img src="@/assets/images/login-pwd.png" alt="" />
            </div>
            <div class="jx-login-form-item captcha" v-if="codeStatus != 200">
              <input type="text" v-model="verCode" placeholder="请输入验证码" />
              <img :src="captcha" @click="verCodeFn" />
            </div>
            <p v-html="errorValue"></p>
            <div class="jx-login-form-item">
              <div class="jx-login-form-submit" @click="Login">登录</div>
            </div>
            <div class="to-home">
                <router-link to="/Teaching/index">返回首页</router-link>
            </div>
          </form>
        </div>
        <el-dialog
          :close-on-click-modal="false"
          class="dialog-show"
          :visible.sync="dialogVisibleShow"
          width="495px"
          @close="closeDialogVisible"
        >
          <div class="ys-dialog-phone">
            <span class="ys-phoneinfo">我们将发送短信验证码到您下面的手机号上</span>
            <p class="ys-phones">{{ tellphones }}</p>
            <div class="ys-login-Code">
              <input
                type="text"
                v-model="VerificationCode"
                maxlength="6"
                placeholder="请输入短信验证码"
              />
              <button v-if="flagCode && !ErrorCode" class="ys-timeDown">
                重新发送&nbsp;{{ timeDown }}
              </button>
              <button v-if="!flagCode && !ErrorCode" class="ys-GetCode" @click="GetCode">
                {{ getin ? "获取验证码" : "重新获取" }}
              </button>
              <button v-if="ErrorCode" class="ys-GetCode" style="color: #c6c6c6">
                {{ getin ? "获取验证码" : "重新获取" }}
              </button>
            </div>
            <p v-html="errorInfo" class="ys-errorInfo"></p>
            <div class="ys-submit" @click="Phonelogin">确定</div>
          </div>
        </el-dialog>
      </div>
    </div>
    <div class="jx-login-footer" v-if="isShowFooter">
      <p>{{ copyrightAttribution }} {{ phoneNumber }}</p>
      <p>{{ address }}</p>
    </div>
  </div>
</template>

<script>
import { getToken, setToken, getName, setName } from "@/utils/auth";
export default {
  data() {
    return {
      account: "", //用户名
      password: "", //密码
      verCode: "", //验证码
      //错误提示
      errorValue: "",
      //判断是否显示验证码
      codeStatus: 200,
      //验证码
      captcha: "",
      // 是否显示版权所有
      isShowFooter: false,
      infoData: "",
      unauthorizedLogoImage: "",
      projectName: "",
      copyrightAttribution: "",
      phoneNumber: "",
      address: "",

      //yx
      //弹窗
      dialogVisibleShow: false,
      //验证码
      VerificationCode: "",
      //验证码标识
      flagCode: false,
      //倒计时初始值
      timeDown: 60,
      getin: true,
      //定时器
      timer: "",
      //电话号码
      tellphones: "",
      //短信错误信息
      errorInfo: "",
      //获取信息或 重新发送置灰
      ErrorCode: false,
      //5分倒计时
      timeDown2: 300,
      timer2: "",
    };
  },
  destroyed() {
    clearInterval(this.timer);
    clearInterval(this.timer2);
  },
  created() {
    let self = this;
    //yx清空缓存值
    self.$localstorage.putLocalStorage("directionList");
    // 拉取信息
    self.loginInfo();
    self.captcha =
      "/tes/unauthorized/image-code?width=75&height=35&time=" + new Date().valueOf();
    //yx修改
    self.isShow();
    self.$nextTick(() => {
      let screenHeight = window.screen.height;

      if (screenHeight >= 900) {
        self.isShowFooter = true;
      } else {
        self.isShowFooter = false;
      }
      window.onresize = function () {
        if (screenHeight >= 900) {
          self.isShowFooter = true;
        } else {
          self.isShowFooter = false;
        }
      };
    });
  },
  methods: {
    // 拉取信息
    loginInfo() {
      let self = this;
      self.$http
        .get(
          "/tes/unauthorized/config?keys=projectName,unauthorizedLogoImage,copyrightAttribution,phoneNumber,address"
        )
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            self.infoData = res.data;
            self.unauthorizedLogoImage = res.data.unauthorizedLogoImage[0].keyValuePath;
            self.projectName = res.data.projectName[0].keyValue;
            self.copyrightAttribution = res.data.copyrightAttribution[0].keyValue;
            self.phoneNumber = res.data.phoneNumber[0].keyValue;
            self.address = res.data.address[0].keyValue;
          } else {
            self.$message.error(res.message);
          }
        })
        .catch((err) => {
          reject(err);
        });
    },
    //yx修改 获取验证码是否显示
    isShow() {
      let self = this;
      self.$http
        .get("/tes/unauthorized/image-code/show")
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            if (res.data) {
              self.codeStatus = "";
            }
          } else {
            self.$message.error(res.message);
          }
        })
        .catch((err) => {
          reject(err);
        });
    },
    //登录
    Login() {
      let self = this,
        userName = self.account,
        userPwd = self.password;
      userName = userName.replace(/(^\s*)|(\s*$)/g, "");
      userPwd = userPwd.replace(/(^\s*)|(\s*$)/g, "");
      if (userName == "") {
        self.errorValue = "请输入账号";
      } else if (userName.length > 20) {
        self.errorValue = "请输入正确账号";
      } else if (userPwd == "") {
        self.errorValue = "请输入密码";
      } else if (userPwd.length > 14) {
        self.errorValue = "请输入正确密码";
      } else if (self.codeStatus != 200 && self.verCode == "") {
        self.errorValue = "请输入验证码";
      } else {
        let formData = new FormData();
        if (this.codeStatus == 200) {
          formData.append("username", userName);
          formData.append("password", userPwd);
        } else {
          formData.append("username", userName);
          formData.append("password", userPwd);
          formData.append("code", self.verCode);
          formData.append("mobileCode", self.VerificationCode);
        }
        return new Promise((resolve, reject) => {
          self.$http
            .post("/tes/unauthorized/form", formData, {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            })
            .then((response) => {
              let res = response.data;
              if (res.code == 200) {
                //错误提示
                self.errorValue = "";
                let roleCode = res.data.roleCode;
                let roles = [];
                roles.push(roleCode);
                //设置token
                setToken(roleCode);
                //vuex提交SET_ROLES角色
                self.$store.commit("SET_ROLES", roles);
                // self.$store.commit('SET_ROLES', roles)
                if (
                  roleCode == "TEACHER" ||
                  roleCode == "STUDENT" ||
                  roleCode == "UNIVERSITY_TEACHER" ||
                  roleCode == "MARKET_TEACHER"
                ) {
                  self.$router.push({ path: "/Teaching/index" });
                  window.location.reload();
                } else if (roleCode == "ADMIN" || roleCode == "SUPER_ADMIN") {
                  self.$router.push({ path: "/Admin/TeachingMange" });
                  window.location.reload();
                } else if (roleCode == "INTERNET_ADMIN") {
                  self.$router.push({ path: "/Admin/Internet/TeachMange" });
                  window.location.reload();
                } else if(
                  roleCode == "COMMENT_TEACHER"
                ){
                  self.$router.push({ path: "/competitionManagement" });
                  window.location.reload();
                }
                resolve();
              } else if (res.code == 100107) {
                self.dialogVisibleShow = true;
                self.tellphones = res.data;
              } else {
                //错误提示
                self.errorValue = res.message;
                self.codeStatus = res.code;
                self.captcha =
                  "/tes/unauthorized/image-code?width=75&height=35&time=" +
                  new Date().valueOf();
              }
            })
            .catch((err) => {
              reject(err);
            });
        });
      }
    },
    //关闭弹窗
    closeDialogVisible() {
      clearInterval(this.timer);
      clearInterval(this.timer2);
      this.timeDown = 60;
      this.timeDown2 = 300;
      this.VerificationCode = "";
      this.flagCode = false;
      this.ErrorCode = false;
      this.errorInfo = "";
    },
    //账号鼠标按下
    accountDown() {
      this.accountActive = false;
      this.accountValue = "请输入帐号";
    },
    //密码鼠标按下
    pwdDown() {
      this.pwdActive = false;
      this.passwordValue = "请输入密码";
    },
    //切换验证码
    verCodeFn() {
      this.captcha =
        "/tes/unauthorized/image-code?width=75&height=35&time=" + new Date().valueOf();
    },
    //yx
    //演示平台新增获取验证码
    GetCode() {
      let self = this;
      clearInterval(self.timer);
      clearInterval(self.timer2);
      this.flagCode = true;
      self.$http.post("/tes/unauthorized/sms-code/send").then((response) => {
        //self.$http.post('/tes/unauthorized/sms-code/send-error').then((response) => {
        let res = response.data;
        if (res.code == "200") {
          self.Down();
          // self.timer = setInterval(()=>{
          //     self.flagCode = true
          //     if(self.timeDown <= 1){
          //         self.timeDown = 60
          //         self.flagCode = false
          //         self.getin = false
          //         clearInterval(self.timer)
          //     }
          //     self.timeDown --

          //  },1000)
          self.VerificationCode = res.data;
          self.errorInfo = "";
        } else {
          self.errorInfo = res.message;
          self.ErrorCode = true;
          self.Down2();

          // self.timer2 = setInterval(()=>{
          //     if(self.timeDown2 <= 1){
          //         clearInterval(self.timer2)
          //         self.timeDown2 = 5
          //         self.flagCode = false
          //         self.ErrorCode = false
          //         self.getin = false
          //     }
          //     self.timeDown2 --

          // },1000)
        }
      });
    },
    //倒计时
    Down() {
      let self = this;
      self.timer = setInterval(() => {
        self.flagCode = true;
        if (self.timeDown <= 1) {
          self.timeDown = 60;
          self.flagCode = false;
          self.getin = false;
          clearInterval(self.timer);
        }
        self.timeDown--;
      }, 1000);
    },
    Down2() {
      let self = this;
      self.timer2 = setInterval(() => {
        if (self.timeDown2 <= 1) {
          clearInterval(self.timer2);
          self.timeDown2 = 300;
          self.flagCode = false;
          self.ErrorCode = false;
          self.getin = false;
        }
        self.timeDown2--;
      }, 1000);
    },
    //短信登陆
    Phonelogin() {
      let reg = /^[0-9]+$/;
      if (this.VerificationCode == "") {
        this.errorInfo = "请输入短信验证码";
        return;
      } else if (!reg.test(this.VerificationCode)) {
        this.errorInfo = "请输入6位数字验证码";
        return;
      }
      let self = this,
        userName = self.account,
        userPwd = self.password;
      userName = userName.replace(/(^\s*)|(\s*$)/g, "");
      userPwd = userPwd.replace(/(^\s*)|(\s*$)/g, "");

      let formData = new FormData();
      formData.append("username", userName);
      formData.append("password", userPwd);
      formData.append("code", self.verCode);
      formData.append("mobileCode", self.VerificationCode);

      // return new Promise((resolve, reject) => {
      self.$http
        .post("/tes/unauthorized/form", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          let res = response.data;
          if (res.code == 200) {
            //错误提示
            self.errorInfo = "";
            let roleCode = res.data.roleCode;
            let roles = [];
            roles.push(roleCode);
            //设置token
            setToken(roleCode);
            //vuex提交SET_ROLES角色
            self.$store.commit("SET_ROLES", roles);
            // self.$store.commit('SET_ROLES', roles)
            if (
              roleCode == "TEACHER" ||
              roleCode == "STUDENT" ||
              roleCode == "UNIVERSITY_TEACHER" ||
              roleCode == "MARKET_TEACHER"
            ) {
              self.$router.push({ path: "/Teaching/index" });
              window.location.reload();
            } else if (roleCode == "ADMIN" || roleCode == "SUPER_ADMIN") {
              self.$router.push({ path: "/Admin/TeachingMange" });
              window.location.reload();
            } else if (roleCode == "INTERNET_ADMIN") {
              self.$router.push({ path: "/Admin/Internet/TeachMange" });
              window.location.reload();
            }
            //resolve()
          } else if (res.code == 100107) {
            self.tellphones = res.data;
            self.errorInfo = res.message;
          } else {
            //错误提示
            self.errorInfo = res.message;
          }
        })
        .catch((err) => {
          console(err);
        });
      // })
    },
  },
};
</script>
<style scoped>
.to-home{
    font-size: 14px;
    text-align: center;
    padding:20px 0;
}
.to-home a{
    color:#ccc;
}
.to-home:hover{
    opacity: .9;
    /* color: #4A90E2; */
}
/* .dialog-show>>>.el-dialog__header{
    display: none
} */
.dialog-show >>> .el-dialog__header {
  border-radius: 10px;
}
.dialog-show >>> .el-dialog__close {
  color: #727272;
  font-size: 17px;
}
.dialog-show >>> .el-dialog__close:hover {
  color: #727272;
}
.dialog-show >>> .el-dialog__header {
  background: #fff;
}
</style>
<style scoped lang="scss">
@import "@/styles/login.scss";
</style>
